import React, { useState } from 'react'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from '@/components/ui/table'
import { ScrollArea } from '@/components/ui/scroll-area'
import ImagePicker from '@/components/ui/image-picker'
import ImageSlicer from '@/components/ui/image-slicer'
import { Toaster } from '@/components/ui/toaster'
import { useToast } from '@/hooks/use-toast'

interface ImageSliceData {
  id: string
  x: number
  y: number
  width: number
  height: number
  name: string
}

export default function ImageDemo() {
  const [selectedImage, setSelectedImage] = useState('')
  const [textContent, setTextContent] = useState('')
  const [imageUrl, setImageUrl] = useState('/api/g/f/p/14097')
  const [sliceData, setSliceData] = useState<ImageSliceData[]>([])
  const [showSlicer, setShowSlicer] = useState(false)
  const [showDataTable, setShowDataTable] = useState(false)
  const { toast } = useToast()

  const handleImageSelect = (imageName: string) => {
    setSelectedImage(imageName)
    setTextContent((prev) => prev + `[${imageName}]`)
  }

  const handleSliceDataGenerated = (data: ImageSliceData[]) => {
    setSliceData(data)
    console.log('Generated slice data:', data)
    toast({
      title: '切片数据已生成',
      description: `成功生成 ${data.length} 个图片切片`
    })
  }

  const exportSliceData = () => {
    const dataStr = JSON.stringify(sliceData, null, 2)
    const dataUri =
      'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr)

    const exportFileDefaultName = 'slice-data.json'

    const linkElement = document.createElement('a')
    linkElement.setAttribute('href', dataUri)
    linkElement.setAttribute('download', exportFileDefaultName)
    linkElement.click()
  }

  const copySliceData = () => {
    navigator.clipboard.writeText(JSON.stringify(sliceData, null, 2))
    toast({
      title: '数据已复制',
      description: '切片数据已复制到剪贴板'
    })
  }

  const loadTestData = () => {
    // 重置为默认配置用于测试 - 5行5列，有间距
    const testData = []
    const cellWidth = 64
    const cellHeight = 64
    const offsetX = 2
    const offsetY = 2
    const rowSpacing = 2
    const colSpacing = 2

    let id = 1
    for (let row = 0; row < 5; row++) {
      for (let col = 0; col < 5; col++) {
        const x = offsetX + col * (cellWidth + colSpacing)
        const y = offsetY + row * (cellHeight + rowSpacing)

        testData.push({
          id: id.toString(),
          x,
          y,
          width: cellWidth,
          height: cellHeight,
          name: `slice_${id}`
        })
        id++
      }
    }
    setSliceData(testData)
    toast({
      title: '测试数据已加载',
      description: '已加载25个测试切片数据'
    })
  }

  return (
    <div className="container mx-auto max-w-6xl p-6">
      <div className="space-y-6">
        <div className="text-center">
          <h1 className="mb-2 text-3xl font-bold">图片切割与选择演示</h1>
          <p className="text-gray-600">从大图中切出小图并制作选择器</p>
          <div className="mt-4 flex justify-center gap-2">
            <Button
              onClick={() => window.open('/img-examples', '_blank')}
              variant="outline"
              size="sm"
            >
              查看使用示例
            </Button>
            <Button
              onClick={() => window.open('/img-gallery', '_blank')}
              variant="outline"
              size="sm"
            >
              图片画廊选择器
            </Button>
          </div>
        </div>

        {/* 快速开始指南 */}
        <Card className="border-blue-200 bg-blue-50 p-6">
          <h2 className="mb-4 text-xl font-semibold text-blue-800">
            🚀 快速开始
          </h2>
          <div className="grid grid-cols-1 gap-4 text-sm md:grid-cols-3">
            <div className="rounded border bg-white p-4">
              <h3 className="mb-2 font-medium text-blue-700">1. 准备图片</h3>
              <p className="text-gray-600">
                输入包含多个小图的大图URL，或使用默认测试图片
              </p>
            </div>
            <div className="rounded border bg-white p-4">
              <h3 className="mb-2 font-medium text-blue-700">2. 配置切片</h3>
              <p className="text-gray-600">
                使用图片切割工具调整网格参数，生成切片数据
              </p>
            </div>
            <div className="rounded border bg-white p-4">
              <h3 className="mb-2 font-medium text-blue-700">3. 选择使用</h3>
              <p className="text-gray-600">
                通过图片选择器选择切片，应用到你的项目中
              </p>
            </div>
          </div>
        </Card>

        {/* 配置区域 */}
        <Card className="p-6">
          <h2 className="mb-4 text-xl font-semibold">⚙️ 基础配置</h2>
          <div className="space-y-4">
            <div>
              <label className="mb-2 block text-sm font-medium">图片 URL</label>
              <Input
                value={imageUrl}
                onChange={(e) => setImageUrl(e.target.value)}
                placeholder="请输入图片URL"
              />
              <p className="mt-1 text-xs text-gray-500">
                建议使用PNG格式的图片，支持透明背景。默认图片是一个测试用的图标集合。
              </p>
            </div>
            <div className="flex flex-wrap gap-2">
              <Button
                onClick={() => setShowSlicer(!showSlicer)}
                variant="outline"
              >
                {showSlicer ? '隐藏' : '显示'}图片切割工具
              </Button>
              <Button onClick={loadTestData} variant="outline">
                加载测试数据
              </Button>
              <Button
                onClick={() => setShowDataTable(!showDataTable)}
                variant="outline"
              >
                {showDataTable ? '隐藏' : '显示'}数据表格
              </Button>
            </div>
            {sliceData.length > 0 && (
              <div className="flex items-center gap-2">
                <Badge variant="secondary">
                  当前切片数量: {sliceData.length}
                </Badge>
                <Button onClick={copySliceData} variant="outline" size="sm">
                  复制数据
                </Button>
                <Button onClick={exportSliceData} variant="outline" size="sm">
                  导出JSON
                </Button>
              </div>
            )}
          </div>
        </Card>

        {/* 图片切割工具 */}
        {showSlicer && (
          <ImageSlicer
            imageUrl={imageUrl}
            onSliceDataGenerated={handleSliceDataGenerated}
          />
        )}

        {/* 数据表格 */}
        {showDataTable && sliceData.length > 0 && (
          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">📊 切片数据表格</h2>
            <ScrollArea className="h-96">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>ID</TableHead>
                    <TableHead>名称</TableHead>
                    <TableHead>X坐标</TableHead>
                    <TableHead>Y坐标</TableHead>
                    <TableHead>宽度</TableHead>
                    <TableHead>高度</TableHead>
                    <TableHead>预览</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sliceData.map((slice) => (
                    <TableRow key={slice.id}>
                      <TableCell>{slice.id}</TableCell>
                      <TableCell>{slice.name}</TableCell>
                      <TableCell>{slice.x}</TableCell>
                      <TableCell>{slice.y}</TableCell>
                      <TableCell>{slice.width}</TableCell>
                      <TableCell>{slice.height}</TableCell>
                      <TableCell>
                        <div
                          className="size-8 rounded border bg-gray-100"
                          style={{
                            backgroundImage: `url(${imageUrl})`,
                            backgroundPosition: `-${slice.x}px -${slice.y}px`,
                            backgroundSize: 'auto'
                          }}
                        />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </ScrollArea>
          </Card>
        )}

        {/* 使用演示 */}
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">🎨 基础使用演示</h2>
            <div className="space-y-4">
              <div className="flex items-center gap-4">
                <label className="text-sm font-medium">选择图片：</label>
                <ImagePicker
                  onImageSelect={handleImageSelect}
                  imageUrl={imageUrl}
                  sliceData={sliceData.length > 0 ? sliceData : undefined}
                  trigger={
                    <Button variant="outline" size="sm">
                      {selectedImage || '📷'} 选择图片
                    </Button>
                  }
                />
                {selectedImage && (
                  <span className="text-sm text-gray-600">
                    已选择: {selectedImage}
                  </span>
                )}
              </div>

              <div>
                <label className="mb-2 block text-sm font-medium">
                  文本内容
                </label>
                <Textarea
                  value={textContent}
                  onChange={(e) => setTextContent(e.target.value)}
                  placeholder="在这里输入文本，然后选择图片插入..."
                  rows={4}
                />
              </div>

              <div className="flex gap-2">
                <Button
                  onClick={() => setTextContent('')}
                  variant="outline"
                  size="sm"
                >
                  清空文本
                </Button>
                <Button
                  onClick={() => {
                    navigator.clipboard.writeText(textContent)
                    toast({
                      title: '文本已复制',
                      description: '文本内容已复制到剪贴板'
                    })
                  }}
                  variant="outline"
                  size="sm"
                >
                  复制文本
                </Button>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">📝 代码示例</h2>
            <div className="space-y-4">
              <div>
                <label className="mb-2 block text-sm font-medium">
                  React 组件使用
                </label>
                <Textarea
                  value={`import ImagePicker from '@/components/ui/image-picker'

function MyComponent() {
  const [selectedImage, setSelectedImage] = useState('')
  const sliceData = ${JSON.stringify(sliceData.slice(0, 3), null, 2)}
  
  return (
    <ImagePicker
      onImageSelect={(imageName) => setSelectedImage(imageName)}
      imageUrl="${imageUrl}"
      sliceData={sliceData}
      trigger={<Button>选择图片</Button>}
    />
  )
}`}
                  readOnly
                  rows={12}
                  className="font-mono text-xs"
                />
              </div>
              <Button
                onClick={() => {
                  const code = `import ImagePicker from '@/components/ui/image-picker'

function MyComponent() {
  const [selectedImage, setSelectedImage] = useState('')
  const sliceData = ${JSON.stringify(sliceData, null, 2)}
  
  return (
    <ImagePicker
      onImageSelect={(imageName) => setSelectedImage(imageName)}
      imageUrl="${imageUrl}"
      sliceData={sliceData}
      trigger={<Button>选择图片</Button>}
    />
  )
}`
                  navigator.clipboard.writeText(code)
                  toast({
                    title: '代码已复制',
                    description: '示例代码已复制到剪贴板'
                  })
                }}
                variant="outline"
                size="sm"
              >
                复制代码
              </Button>
            </div>
          </Card>
        </div>

        {/* 使用说明 */}
        <Card className="p-6">
          <h2 className="mb-4 text-xl font-semibold">📖 使用说明</h2>
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
            <div className="space-y-4">
              <div>
                <h3 className="mb-2 font-medium">1. 准备图片</h3>
                <p className="text-sm text-gray-600">
                  准备一个包含多个小图的大图，图片应该按网格排列。推荐使用PNG格式支持透明背景。
                </p>
                <div className="mt-2 rounded bg-gray-50 p-2 text-xs">
                  💡 提示：图片建议尺寸不超过2048x2048，以确保加载性能
                </div>
              </div>
              <div>
                <h3 className="mb-2 font-medium">2. 配置网格参数</h3>
                <p className="text-sm text-gray-600">
                  使用图片切割工具来调整网格参数：
                </p>
                <ul className="mt-2 space-y-1 text-xs text-gray-600">
                  <li>• 行数/列数：网格的行列数量</li>
                  <li>• 切片宽度/高度：每个小图的尺寸</li>
                  <li>• 行间距/列间距：小图之间的间距</li>
                  <li>• X偏移/Y偏移：起始位置的偏移量</li>
                </ul>
              </div>
              <div>
                <h3 className="mb-2 font-medium">3. 预览和调整</h3>
                <p className="text-sm text-gray-600">
                  点击&quot;生成预览&quot;按钮查看切图效果，可以看到网格覆盖层和实际切出的小图预览。
                </p>
              </div>
            </div>
            <div className="space-y-4">
              <div>
                <h3 className="mb-2 font-medium">4. 生成和使用配置</h3>
                <p className="text-sm text-gray-600">
                  点击&quot;生成配置&quot;按钮，配置数据会自动复制到剪贴板。你可以：
                </p>
                <ul className="mt-2 space-y-1 text-xs text-gray-600">
                  <li>• 直接在代码中使用这些数据</li>
                  <li>• 导出为JSON文件保存</li>
                  <li>• 在其他项目中重复使用</li>
                </ul>
              </div>
              <div>
                <h3 className="mb-2 font-medium">5. 组件集成</h3>
                <p className="text-sm text-gray-600">
                  将切片数据传递给 ImagePicker 组件：
                </p>
                <ul className="mt-2 space-y-1 text-xs text-gray-600">
                  <li>• 用户可以通过弹窗选择图片</li>
                  <li>• 支持自定义触发按钮</li>
                  <li>• 自动处理图片切割和显示</li>
                </ul>
              </div>
            </div>
          </div>
        </Card>

        {/* 应用场景 */}
        <Card className="p-6">
          <h2 className="mb-4 text-xl font-semibold">🎯 应用场景</h2>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
            <div className="rounded bg-gradient-to-br from-blue-50 to-blue-100 p-4 text-center">
              <div className="mb-2 text-2xl">🎮</div>
              <h3 className="mb-1 font-medium">游戏开发</h3>
              <p className="text-xs text-gray-600">
                道具图标、角色头像、技能图标
              </p>
            </div>
            <div className="rounded bg-gradient-to-br from-green-50 to-green-100 p-4 text-center">
              <div className="mb-2 text-2xl">💬</div>
              <h3 className="mb-1 font-medium">聊天应用</h3>
              <p className="text-xs text-gray-600">表情包、贴纸、动态图标</p>
            </div>
            <div className="rounded bg-gradient-to-br from-purple-50 to-purple-100 p-4 text-center">
              <div className="mb-2 text-2xl">📝</div>
              <h3 className="mb-1 font-medium">内容编辑</h3>
              <p className="text-xs text-gray-600">富文本编辑器、图标插入</p>
            </div>
            <div className="rounded bg-gradient-to-br from-orange-50 to-orange-100 p-4 text-center">
              <div className="mb-2 text-2xl">🎨</div>
              <h3 className="mb-1 font-medium">UI设计</h3>
              <p className="text-xs text-gray-600">
                图标库、按钮状态、装饰元素
              </p>
            </div>
          </div>
        </Card>

        {/* 技术方案 */}
        <Card className="p-6">
          <h2 className="mb-4 text-xl font-semibold">⚡ 技术方案</h2>
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
            <div className="space-y-3">
              <div>
                <h3 className="flex items-center gap-2 font-medium">
                  <span className="size-2 rounded-full bg-blue-500"></span>
                  Canvas 切图方案
                </h3>
                <p className="ml-4 text-sm text-gray-600">
                  使用 Canvas API 从大图中切出小图，转换为 base64 格式显示
                </p>
                <div className="ml-4 mt-2 space-y-1 text-xs">
                  <div className="text-green-600">
                    ✓ 灵活性高，可以处理任意布局
                  </div>
                  <div className="text-orange-600">⚠ 首次加载需要处理时间</div>
                </div>
              </div>
              <div>
                <h3 className="flex items-center gap-2 font-medium">
                  <span className="size-2 rounded-full bg-green-500"></span>
                  CSS Background 方案
                </h3>
                <p className="ml-4 text-sm text-gray-600">
                  使用 CSS background-position 显示大图的特定部分
                </p>
                <div className="ml-4 mt-2 space-y-1 text-xs">
                  <div className="text-green-600">✓ 性能好，加载快</div>
                  <div className="text-orange-600">⚠ 需要精确的位置计算</div>
                </div>
              </div>
            </div>
            <div className="space-y-3">
              <div>
                <h3 className="flex items-center gap-2 font-medium">
                  <span className="size-2 rounded-full bg-purple-500"></span>
                  性能优化
                </h3>
                <ul className="ml-4 space-y-1 text-xs text-gray-600">
                  <li>• 图片懒加载：只加载可见区域</li>
                  <li>• 缓存机制：避免重复处理</li>
                  <li>• 压缩优化：合理设置图片质量</li>
                  <li>• CDN加速：提升加载速度</li>
                </ul>
              </div>
              <div>
                <h3 className="flex items-center gap-2 font-medium">
                  <span className="size-2 rounded-full bg-red-500"></span>
                  扩展功能
                </h3>
                <ul className="ml-4 space-y-1 text-xs text-gray-600">
                  <li>• 批量处理多个图片文件</li>
                  <li>• 自定义切片形状（圆形、多边形）</li>
                  <li>• 动态切片检测</li>
                  <li>• 图片格式转换</li>
                </ul>
              </div>
            </div>
          </div>
        </Card>
      </div>
      <Toaster />
    </div>
  )
}
